//
//  StatusesViewModel.swift
//  SinaWeiBo
//
//  Created by dengchen on 15/11/14.
//  Copyright © 2015年 name. All rights reserved.
//

import UIKit
import SDWebImage

class StatusesViewModel {

    static let shared = StatusesViewModel()
    
    func loadStatuses(since_id since_id :Int = 0,max_id:Int = 0,finished:(modelData:[statusModel]?) ->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var param = ["access_token":UserAccountOAuthModel.shared.Account!.access_token!]
        
        if since_id > 0 {
            param["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            param["max_id"] = "\(max_id - 1)"
        }
        
        NetWorkTool.shared.requestData("GET", URLString: urlString, parameters: param, success: { (result) -> Void in
            
            var mutableArr = [statusModel]()

            if let dict = result as? [String:AnyObject] {   //将返回的结果转换成字典

                if let arr = dict["statuses"] as? [[String:AnyObject]] {  //取出字典中的字典数组

                    for item in arr {   //遍历字典数组
                    
                       let md = statusModel(dict: item)
                        
                        mutableArr.append(md) //字典转模型
                    }
                    
                }
            }
            
            self.downloadSingleImage(mutableArr, finished: finished)
            
            }) { (error) -> Void in
                
            finished(modelData: nil)
                
        }
        
    }
    
    private func downloadSingleImage(array:[statusModel],finished:(modelData:[statusModel]?) ->()) {
        
        if array.count < 1 {
            finished(modelData: nil)
            return
        }
        
        let group = dispatch_group_create()
        
        for md in array {
            
            
//        guard let imageUrls = md.imageURLs where imageUrls.count != 1 else {continue}
            var imageUrl:NSURL?
            
            if md.imageURLs?.count != 1 {
                if md.retweeted_status?.imageURLs?.count != 1 {
                    continue
                }else {
                    imageUrl = md.retweeted_status?.imageURLs?.first
                    print("转发微博图片url\(imageUrl)")
                }
            }else {
                imageUrl = md.imageURLs?.first
                print("原创微博图片url\(imageUrl)")
            }
            
                dispatch_group_enter(group)
            
            SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                dispatch_group_leave(group)
            })
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //在主线程完成回调
            print("所有的异步图片下载完成")
            finished(modelData: array)
        }
        
    }
        
        
}
    

